<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/welcom' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-row>
        <el-col>
          <el-button
            type="primary"
            @close="addFormClose"
            @click="showAddLogVisible"
            >添加角色</el-button
          >
        </el-col>
      </el-row>

      <el-table :data="roleList">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bdBtomn', i1 === 0 ? 'bdTop' : '', 'vCenter']"
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="5">
                <el-tag
                  @close="deleteRightById(scope.row, item1.id)"
                  closable
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  :class="[i2 !== 0 ? 'bdTop' : '', 'vCenter']"
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      @close="deleteRightById(scope.row, item2.id)"
                      closable
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="13">
                    <el-tag
                      v-for="(item3, i3) in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="deleteRightById(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="角色操作">
          <template slot-scope="scop">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="showEditlogVisible(scop.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="deleteRole(scop.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              @click="showRoleRight(scop.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加角色 -->

    <el-dialog
      title="添加"
      :visible.sync="addLogVisible"
      width="30%"
      @close="addFormClose"
    >
      <el-form :rules="addFormRules" :model="addForm" ref="addFormRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addLogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editLogVisible"
      width="30%"
      @close="editFormClose"
    >
      <el-form
        :model="editForm"
        :rules="editFormrules"
        ref="editFormRef"
        label-width="80px"
      >
        <el-form-item label="角色Id">
          <el-input v-model="editForm.roleId" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editLogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 权限列表 -->
    <el-dialog
      title="权限列表"
      :visible.sync="allRightlogVisible"
      width="30%"
      @close="setRoleRightClose"
    >
      <el-tree
        :data="roleRightsList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        ref="treeRef"
        default-expand-all
        :default-checked-keys="defKey"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="allRightlogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setCurrenRoleRight">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'roles',
  data() {
    return {
      roleList: [],
      editLogVisible: false,
      editForm: {},
      editFormrules: {
        roleName: { required: true, message: '请输入邮箱', trigger: 'blur' },
        roleDesc: { required: true, message: '请输入邮箱', trigger: 'blur' },
      },
      addLogVisible: false,
      addForm: {
        roleId: '',
        roleName: '',
        roleDesc: '',
      },
      addFormRules: {
        roleId: [
          { required: true, message: '请输入角色Id', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],

        roleName: [
          { required: true, message: '请输入角色Id', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
        roleDesc: [
          { required: true, message: '请输入角色Id', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur',
          },
        ],
      },

      allRightlogVisible: false,
      roleRightsList: [],
      treeProps: {
        label: 'authName',
        children: 'children',
      },
      defKey: [],
      roleId: 0,
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    show(id) {
      console.log(id)
    },
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$Message.error('请求角色失败')
      this.roleList = res.data
    },
    async showEditlogVisible(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      this.editForm = res.data
      this.editLogVisible = true
    },
    editFormClose() {
      this.$refs.editFormRef.resetFields()
    },
    editRole() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'roles/' + this.editForm.roleId,
          {
            roleName: this.editForm.roleName,
            roleDesc: this.editForm.roleDesc,
          }
        )
        if (res.meta.status !== 200) return this.$Message.error('修改失败')
        this.$Message.success('修改成功')
      })
      this.getRoleList()
      this.editLogVisible = false
    },
    showAddLogVisible() {
      this.addLogVisible = true
    },
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((element) => {
        this.getLeafKeys(element, arr)
      })
    },

    // 添加角色
    addRole() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) return this.$Message.error('添加失败')
        this.$Message.success('添加成功')
        this.getRoleList()
        this.addLogVisible = false
      })
    },
    addFormClose() {
      this.$refs.addFormRef.resetFields()
    },
    async deleteRole(id) {
      const deleteRoleRef = await this.$confirm('确定要删除吗？', '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonText: '继续删除',
        cancelButtonText: '取消删除',
      }).catch((err) => err)

      if (deleteRoleRef != 'confirm') {
        return this.$Message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$Message.error('删除失败')

      this.$Message.success('删除成功')
      this.getRoleList()
    },
    async deleteRightById(role, rightId) {
      const deleteRightConfirm = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (deleteRightConfirm !== 'confirm') {
        return this.$Message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) return this.$Message.error('删除失败')
      this.$Message.success('删除成功')

      role.children = res.data
    },
    async showRoleRight(role) {
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return this.$Message.error('请求权限失败')
      this.roleRightsList = res.data
      this.getLeafKeys(role, this.defKey)
      this.allRightlogVisible = true
    },
    setRoleRightClose() {
      this.defKey = []
    },
    async setCurrenRoleRight() {
      const Keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      const idstr = Keys.join(',')
      console.log(idstr);
     
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idstr }
      )
      if (res.meta.status !== 200) this.$Message.error('请求失败')
      this.$Message.success('请求成功')
      this.getRoleList()
      this.allRightlogVisible = false
    },
  },
}
</script>

<style scoped>
.el-card {
  margin-top: 10px;
}
.el-tag {
  margin: 7px;
}
.bdBtomn {
  border-bottom: 1px solid black;
}
.bdTop {
  border-top: 1px solid black;
}

.vCenter {
  display: flex;
  align-items: center;
}
</style>